package com.android.dblocation

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.lifecycle.LifecycleService

class DBLocationService : LifecycleService() {

    private val CHANNEL_ID = "db_location_service_channel"
    private val NOTIFICATION_ID = 1

    lateinit var mBinder:DBLocationBinder

    override fun onCreate() {
        super.onCreate()
        mBinder = DBLocationBinder(applicationContext)

        createNotificationChannel()
        startForegroundService()
    }

    override fun onBind(intent: Intent): IBinder? {
        super.onBind(intent)
        return mBinder
    }

    override fun onUnbind(intent: Intent?): Boolean {

        return super.onUnbind(intent)
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val serviceChannel = NotificationChannel(
                CHANNEL_ID,
                "DBLocationService Channel",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            manager.createNotificationChannel(serviceChannel)
        }
    }

    @SuppressLint("ForegroundServiceType")
    private fun startForegroundService() {
        val notification: Notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("正在使用定位")
            .setContentText("后台正在使用定位")
            .setSmallIcon(android.R.drawable.ic_menu_mylocation)
            .setSilent(true)
            .setSound(null)
            .setDefaults(0)
            .build()

        startForeground(NOTIFICATION_ID, notification)
    }
}
